package cc.telecomdigital.tdstock;

import java.util.HashMap;

import android.content.Context;
import android.content.SharedPreferences;

import cc.telecomdigital.tdstock.CommonDefn.DataMode;
//import cc.telecomdigital.tdstock.CommonDefn.Environment;
import cc.telecomdigital.tdstock.CommonDefn.ModeType;
import cc.telecomdigital.tdstock.Framework.Application_Framework;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog.DEBUG_LVL;
import cc.telecomdigital.tdstock.Http.Services.HttpAppInfo;
import cc.telecomdigital.tdstock.Services.LS_ClientParamMemory;
import cc.telecomdigital.tdstock.activity.groups.more.push.util.Data;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppBannerDataSet;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;

/**
 * Singleton Object as a global variable, associate to View and Activity.
 * 
 * 
 * 
 * @author haibo
 * 
 */
public class ITDLApplication extends Application_Framework
{
	private static final String	TAG	= "ITDLApplication";
	private static boolean isDevelopment = true;

	//Our pretty construction for some setting
	public ITDLApplication()
	{
		super();
		// Set Debug level only to show error, do not set or preset at other
		// module
		// The purpose is to diminish the expose of source
		TDStockLog.SetDebugLevel(DEBUG_LVL.DEBUG);
		// Our Production environment
		LS_ClientParamMemory.SetAsDevelopment(isDevelopment);
		TradeAppInfo.SetAsDevelopment(isDevelopment);
	}

	@Override
	public void onCreate()
	{
		super.onCreate();
		
		DeviceIdSharedPrefTools.Init(this); //First initialize
		
		// Load adv figure to database if needed
		if (TradeAppInfo.TradeApp_Ready)
		{
			Trade_AppBannerDataSet.InitAppBannerStorage(this);
			TradeAppInfo.Initialize(this);
		}		
	    HttpAppInfo.Init(this);
	}

	private String state;
	private Object object;
	private int id;
	private boolean isAuthComeFromActivationCode;
	
	private String svcPlan;
	
	public String GetServicePlan()
	{
		return svcPlan;
	}
	
	public void SetServicePlan(String iSvcPlan)
	{
		svcPlan = iSvcPlan;
		
		// "Betting" index=17
//		setIsBetting(!svcPlan.substring(16,17).equals("0"));
		// "BMP Mode" index=15
		setIsBMPMode(!svcPlan.substring(14,15).equals("0"));
		// "查閱用量" index=14
		setIsCheckUsageType(svcPlan.substring(13,14));
		// "Horse" index=13
//		setIsHorse(!svcPlan.substring(12, 13).equals("0"));
		// "Soccer" index=12
//		setIsSoccer(!svcPlan.substring(11, 12).equals("0"));
		// "期指" index=2
		setIsRealtimeFutures(svcPlan.substring(1, 2).equals("1"));
		// "上証" index=5
		setIsRealtimeSSEI(svcPlan.substring(4, 5).equals("1"));
		
		setLightStreamerUnlimit(svcPlan.substring(10, 11).equalsIgnoreCase("Z"));
	}
	
	/**
	 * 能否進入 "Betting", 需要視乎 svc plan 中的 flag 17: flagValue == 0 -> false
	 * flagValue != 0 -> true
	 */
//	private boolean isBetting; // svc plan = 17
//
//	public boolean getIsBetting() {
//		return isBetting;
//	}
//
//	public void setIsBetting(boolean isBetting) {
//		// isBetting = true;
//		this.isBetting = isBetting;
//	}
	
	/**
	 * 能否進入 "BMP Mode", 需要視乎 svc plan 中的 flag 15: flagValue == 0 -> false
	 * flagValue != 0 -> true
	 */
	private boolean isBMPMode; // svc plan = 15

	public boolean getIsBMPMode() {
		return isBMPMode;
	}

	public void setIsBMPMode(boolean isBMPMode) {
		// isBMPMode = true;
		this.isBMPMode = isBMPMode;
	}

	/**
	 * 能否進入 "賽馬" 或 "足球", 需要視乎 svc plan 中的 flag 13 和 flag 12: flagValue == 0 ->
	 * false flagValue != 0 -> true
	 */
//	private boolean isHorse; // svc plan = 13
//	private boolean isSoccer;// svc plan = 12
//
//	public boolean getIsHorse() {
//		return isHorse;
//	}
//
//	public void setIsHorse(boolean isHorse) {
//		// isHorse = false;
//		this.isHorse = isHorse;
//	}
//
//	public boolean getIsSoccer() {
//		return isSoccer;
//	}
//
//	public void setIsSoccer(boolean isSoccer) {
//		// isSoccer = false;
//		this.isSoccer = isSoccer;
//	}

	/**
	 * 查閱用量（falg = Delta charge） svc_plan (index=14)value=0,1,2
	 */
	private String isCheckUsageType;

	public String getIsCheckUsageType() {
		return isCheckUsageType;
	}

	public void setIsCheckUsageType(String isCheckUsageType) {
		this.isCheckUsageType = isCheckUsageType;
	}

	/**
	 * 期指（Futures） svc_plan (index = 2)
	 */
	private boolean isRealtimeFutures;

	public boolean getIsRealtimeFutures() {
		return isRealtimeFutures;
	}

	public void setIsRealtimeFutures(boolean isRealtimeFutures) {
		// isRealtimeFutures = false;
		this.isRealtimeFutures = isRealtimeFutures;
	}

	/**
	 * 上証（SSEI） svc_plan (index = 5)
	 */
	private boolean isRealtimeSSEI;

	public boolean getIsRealtimeSSEI() {
		return isRealtimeSSEI;
	}

	public void setIsRealtimeSSEI(boolean isRealtimeSSEI) {
		// isRealtimeSSEI = false;
		this.isRealtimeSSEI = isRealtimeSSEI;
	}

	/**
	 * note that the "Streaming time" is controlled by the 11th flag of svc_plan
	 * (svc_plan[11]) 0 = default time is 60 sec Z = unlimit
	 */
	private boolean isLightStreamerUnlimit;

	public boolean isLightStreamerUnlimit() {
		return isLightStreamerUnlimit;
	}

	public void setLightStreamerUnlimit(boolean isLightStreamerUnlimit) {
		// this.isLightStreamerUnlimit = false;
		this.isLightStreamerUnlimit = isLightStreamerUnlimit;
	}

//	private CdrSender cdrSender;
//
//	public CdrSender getCdrSender() {
//		return cdrSender;
//	}
//
//	public void setCdrSender(CdrSender cdrSender) {
//		this.cdrSender = cdrSender;
//	}

	private long pageLeaveTime; // ms
	private long pageEnterTimer; // ms

	public long getPageLeaveTime() {
		return pageLeaveTime;
	}

	public void setPageLeaveTime(long pageLeaveTime) {
		this.pageLeaveTime = pageLeaveTime;
	}

	public long getPageEnterTimer() {
		return pageEnterTimer;
	}

	public void setPageEnterTimer(long pageEnterTimer) {
		this.pageEnterTimer = pageEnterTimer;
	}

	private boolean isLightStreamerConnected = false;
	private boolean isResetCDR = false;
	public static final int DEFAULT_INT_VALUE = -9999;

	// protected LSClient lightStreamerClient;

//	private boolean isTrial;
	private boolean isExitApp;
	private boolean isTimeChartInBackground;
	private boolean isAdShowed;
	private boolean isLastSafelyExitApp = true;
	private boolean isReadyToChangeMode = false;

	public boolean isReadyToChangeMode() {
		return isReadyToChangeMode;
	}

	public void setReadyToChangeMode(boolean isReadyToChangeMode) {
		this.isReadyToChangeMode = isReadyToChangeMode;
	}

	/**
	 * 
	 * @return false: unexpected restart(usually caused by anr) / true: normal
	 *         startup
	 */
	public boolean isLastSafelyExitApp() {
		return isLastSafelyExitApp;
	}

//	private Environment environment;

	private DataMode dataMode;
	private ModeType modeType;

	/*
	 * private Class<?> currentActivityClass;
	 * 
	 * public Class<?> getCurrentActivityClass() { return currentActivityClass;
	 * } public void setCurrentActivityClass(Class<?> currentActivityClass) {
	 * this.currentActivityClass = currentActivityClass; }
	 */
	public boolean isExitApp() {
		return isExitApp;
	}

	public void setExitApp(boolean isExitApp) {
		this.isExitApp = isExitApp;
	}


	public boolean isTimeChartInBackground() {
		return isTimeChartInBackground;
	}

	public void setTimeChartInBackground(boolean isTimeChartInBackground) {
		this.isTimeChartInBackground = isTimeChartInBackground;
	}

	public boolean isLightStreamerConnected() {
		return isLightStreamerConnected;
	}

	public void setLightStreamerConnected(boolean isLightStreamerConnected) {
		this.isLightStreamerConnected = isLightStreamerConnected;
	}

	public boolean isResetCDR() {
		return isResetCDR;
	}

	public void setResetCDR(boolean isResetCDR) {
		this.isResetCDR = isResetCDR;
	}

	private static HashMap<String, String> _stringHashMap = new HashMap<String, String>();
	private static HashMap<String, Integer> _intHashMap = new HashMap<String, Integer>();

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public Object getObject() {
		return object;
	}

	public void setObject(Object object) {
		this.object = object;
	}

	public String getString(String entry) {
		return _stringHashMap.get(entry);
	}

	public void putString(String key, String value) {
		_stringHashMap.put(key, value);
	}

	public String getUserName(String defaultUser) {
		String result = _stringHashMap.get(CommonDefn.ACCOUNT_USER_KEY);
		if(result==null)
		{
			SharedPreferences _prefs = getSharedPreferences(
					CommonDefn.SYSTEM_CURRENT_SETTING,
					Context.MODE_PRIVATE);
			          result = _prefs.getString(
					CommonDefn.PREFERENCE_LAST_ACCOUNT_NAME, null);
			
		}
		return result == null ? defaultUser : result;
	}

	public String getPwd(String defaultRelatedPwd) {
		String result = _stringHashMap.get(CommonDefn.ACCOUNT_PWD_KEY);
		if(result==null)
		{
			SharedPreferences _prefs = getSharedPreferences(
					CommonDefn.SYSTEM_CURRENT_SETTING,
					Context.MODE_PRIVATE);
			          result = _prefs.getString(
					CommonDefn.PREFERENCE_LAST_ACCOUNT_PWD,null);
			
		}
		return result == null ? defaultRelatedPwd : result;
	}

	public void setDeviceId(String deviceId) {
		_stringHashMap.put(CommonDefn.DEVICE_ID, deviceId);
	}

	public String getDeviceId() {
		String result = _stringHashMap.get(CommonDefn.DEVICE_ID);
		if (result == null) {
			isLastSafelyExitApp = false;
			TDStockLog.d(TAG, "Last safely exit app =" + (isLastSafelyExitApp ? "true" : "false"));
		}
		return result == null ? "null" : result;
	}

	public void setUserName(String user) {
		_stringHashMap.put(CommonDefn.ACCOUNT_USER_KEY, user);
	}

	public void setPwd(String pwd) {
		_stringHashMap.put(CommonDefn.ACCOUNT_PWD_KEY, pwd);
	}

	public int getInt(String entry) {
		if (!_intHashMap.containsKey(entry)) {
			return DEFAULT_INT_VALUE;
		}
		return _intHashMap.get(entry);
	}

	public String getPreferRsiTerm() {
		return _stringHashMap.get(CommonDefn.CUSTOMER_PREFER_RSI_TERM) == null ? "14" : _stringHashMap.get(CommonDefn.CUSTOMER_PREFER_RSI_TERM);
	}

	public void setPreferRsiTerm(String term) {
		_stringHashMap.put(CommonDefn.CUSTOMER_PREFER_RSI_TERM, term);
	}

	public void putInt(String key, int value) {
		_intHashMap.put(key, value);
	}

	public void setUserId(int id) {
		_intHashMap.put(CommonDefn.ACCOUNT_USER_ID_KEY, 1); // hard code by
		// haibo, 2011-04-26
		// _intHashMap.put(CommonDefn.ACCOUNT_USER_ID_KEY, id);
	}

	public int getUserId(int defaultId) {
		return _intHashMap.get(CommonDefn.ACCOUNT_USER_ID_KEY) == null ? defaultId : _intHashMap.get(CommonDefn.ACCOUNT_USER_ID_KEY);
	}

	public void setCurrentNaviBtnId(int id) {
		_intHashMap.put(CommonDefn.CURRENT_NAVIGATION_BTN_RES_ID, id);
	}

	public int getCurrentNaviBtnId(int defaultId) {
		return _intHashMap.get(CommonDefn.CURRENT_NAVIGATION_BTN_RES_ID) == null ? defaultId : _intHashMap.get(CommonDefn.CURRENT_NAVIGATION_BTN_RES_ID);
	}

	public void setCurrentStockCode(String stockCode) {
		_stringHashMap.put(CommonDefn.CURRENT_STOCK_INFO_CODE, stockCode);
	}

	public String getCurrentStockCode() {
		String result = _stringHashMap.get(CommonDefn.CURRENT_STOCK_INFO_CODE);
		return result;
	}

	public void setCurrentStockName(String stockName) {
		_stringHashMap.put(CommonDefn.CURRENT_STOCK_INFO_NAME, stockName);
	}

	public String getCurrentStockName() {
		String result = _stringHashMap.get(CommonDefn.CURRENT_STOCK_INFO_NAME);
		return result;
	}

	public void setSessionToken(String token) {
//		TDStockLog.i("SESSION_TAG", "UpdateKey: " + token);
//		_stringHashMap.put(CommonDefn.CURRENT_SESSION_TOKEN, token);
	}

	public void setSessionAccount(String account) {
//		_stringHashMap.put(CommonDefn.CURRENT_SESSION_ACCOUNT, account);
	}

	public String getSessionToken() {
//		return _stringHashMap.get(CommonDefn.CURRENT_SESSION_TOKEN);
		return GetLSClient_SessionKey();
	}

	public String getSessionAccount() {
//		return _stringHashMap.get(CommonDefn.CURRENT_SESSION_ACCOUNT);
		return GetLSClient_AccountLogonName();
	}

	public boolean isAuthComeFromActivationCode() {
		return isAuthComeFromActivationCode;
	}

	public void setAuthComeFromActivationCode(boolean isAuthComeFromActivationCode) {
		this.isAuthComeFromActivationCode = isAuthComeFromActivationCode;
	}

//	public Environment getEnvironment() {
//		if (environment == null) {
//			isLastSafelyExitApp = false;
//			TDStockLog.d(TAG, "Last safely exit app =" + (isLastSafelyExitApp ? "true" : "false"));
//		}
//		return environment == null ? Environment.Testing : environment;
//	}
//
//	public void setEnvironment(Environment environment) {
//		this.environment = environment;
////		CustomerInfo.setEnvironment(environment);
//	}

	public DataMode getDataMode() {
		if (dataMode == null) {
			isLastSafelyExitApp = false;
			TDStockLog.d(TAG, "Last safely exit app =" + (isLastSafelyExitApp ? "true" : "false"));
		}
		return dataMode == null ? DataMode.Delay : dataMode;
	}

	public void setDataMode(DataMode dataMode) {
		isLastSafelyExitApp = true;
		this.dataMode = dataMode;
	}

	public ModeType getModeType() {
		return this.modeType == null ? ModeType.DELARY : this.modeType;
	}

	public void setModeType(ModeType modeType) {
		this.modeType = modeType;
	}

//	public String getAdapterSet() {
//		String result = CommonDefn.ADAPTER_SET_FOR_CHARGE;
//		if (/*
//			 * getEnvironment() == Environment.Testing &&
//			 */getDataMode() == DataMode.Delay) {
//			result = CommonDefn.ADAPTER_SET_FOR_FREE;
//		}
//		return result;
//	}

	public boolean isAdShowed() {
		return isAdShowed;
	}

	public void setAdShowed(boolean isAdShowed) {
		this.isAdShowed = isAdShowed;
	}

//	public String getWebServer() {
//		String result = null;
//		switch (getEnvironment()) {
//		case Testing:
//			switch (getDataMode()) {
//			case Realtime:
//				result = CommonDefn.WEB_SERVER_HOST_0;
//				break;
//			case Delay:
//				result = CommonDefn.WEB_SERVER_HOST_0;
//				break;
//			}
//			break;
//
//		case Production:
//			switch (getDataMode()) {
//			case Realtime:
//				result = CommonDefn.WEB_SERVER_HOST_PRODUCTION_0;
//				break;
//			case Delay:
//				result = CommonDefn.WEB_SERVER_HOST_PRODUCTION_1;
//				break;
//			}
//			break;
//		}
//		return result;
//	}
//
//	public String getLightStreamer() {
//		String result = null;
//		switch (getEnvironment()) {
//		case Testing:
//			switch (getDataMode()) {
//			case Realtime:
//				result = CommonDefn.LIGHT_STREAMER_HOST_0 + CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.LIGHT_STREAMER_PORT_0;
//				break;
//			case Delay:
//				result = CommonDefn.LIGHT_STREAMER_HOST_0 + CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.LIGHT_STREAMER_PORT_0;
//				// result = CommonDefn.LIGHT_STREAMER_HOST_1 +
//				// CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.
//				// LIGHT_STREAMER_PORT_1;
//				break;
//			}
//			break;
//
//		case Production:
//			switch (getDataMode()) {
//			case Realtime:
//				// result = CommonDefn.LIGHT_STREAMER_HOST_PRODUCTION_0 +
//				// CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.
//				// LIGHT_STREAMER_PORT_PRODUCTION_0;
//				result = CommonDefn.LIGHT_STREAMER_HOST_PRODUCTION_0 + CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.LIGHT_STREAMER_PORT_PRODUCTION_0;
//				break;
//			case Delay:
//				result = CommonDefn.LIGHT_STREAMER_HOST_PRODUCTION_1 + CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.LIGHT_STREAMER_PORT_PRODUCTION_1;
//				// result = CommonDefn.LIGHT_STREAMER_HOST_PRODUCTION_1 +
//				// CommonDefn.HOST_PORT_SEPARATOR + CommonDefn.
//				// LIGHT_STREAMER_PORT_PRODUCTION_1;
//				break;
//			}
//			break;
//		}
//
//		TDStockLog.d(TAG, "is using lightstreamer  =" + (result));
//		return result;
//	}

	// public class DefaultExceptionHandler implements UncaughtExceptionHandler
	// {
	// @Override
	// public void uncaughtException(final Thread thread, Throwable ex) {
	// // cleanup, don't know if really required
	// //call original handler
	//					
	// new AlertDialog.Builder(ITDLApplication.this)
	// .setTitle(getResources().getString(R.string.info))
	// .setMessage(ex.getMessage() == null ? "unknow exception happend!" :
	// ex.getMessage())
	// .setIcon(getResources().getDrawable(R.drawable.help_menu_icon))
	// .setPositiveButton(getResources().getString(R.string.ok),
	// new DialogInterface.OnClickListener(){
	// public void onClick(DialogInterface dialoginterface, int i){
	// thread.getThreadGroup().destroy();
	// Intent forwardToMainActivity = new
	// Intent(getApplicationContext(),LoginActivity.class);
	// ITDLApplication.this.startActivity(forwardToMainActivity);
	// }
	// })
	// .show(); //show failure message;
	//				
	// }
	//			
	// }

	// public LSClient getLightStreamerClient()
	// {
	// if (lightStreamerClient == null)
	// {
	// isLightStreamerConnected = false;
	// lightStreamerClient = new LSClient();
	// }
	// return lightStreamerClient;
	// }
	//
	// public LSClient getLightStreamerClientForNew()
	// {
	// if (lightStreamerClient != null)
	// {
	// isLightStreamerConnected = false;
	// lightStreamerClient.closeConnection();
	// lightStreamerClient = null;
	// }
	// return getLightStreamerClient();
	// }

	/*
	 * public void setLightStreamerClient(LSClient lightStreamerClient) {
	 * this.lightStreamerClient = lightStreamerClient; }
	 */

	@Override
	public void onTerminate() {

		// destroy lightstreamer
		// if (lightStreamerClient != null)
		// {
		// lightStreamerClient.closeConnection();
		// lightStreamerClient = null;
		// }
		// destroy lightstreamer

		if (_stringHashMap != null) {
			_stringHashMap = null;
		}

		if (_intHashMap != null) {
			_intHashMap = null;
		}
		super.onTerminate();
	}

	@Override
	public void onLowMemory() {
		TDStockLog.d(TAG, "the mobile is  under lower memory! ");
		super.onLowMemory();
	}
}
